package io.mvvm.nio;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * @program: Netty
 * @description: Buffer
 * @author: 潘
 * @create: 2021-01-17 19:58
 **/
public class BufferDemo {

    public static void main(String[] args) {
        // BufferUnderflowException Example
//        ByteBuffer buffer = ByteBuffer.allocate(1024);
//        buffer.putShort((short) 10);
//        buffer.flip();
//        buffer.getInt();

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.put("zhangsan".getBytes(StandardCharsets.UTF_8));
        // 读取
        buffer.flip();
        // 得到一个只读的 buffer
        ByteBuffer readOnlyBuffer = buffer.asReadOnlyBuffer();
        System.out.println(readOnlyBuffer.getClass());
        // 读取
        while (readOnlyBuffer.hasRemaining()) {
            System.out.println(readOnlyBuffer.get());
        }
        // Exception in thread "main" java.nio.ReadOnlyBufferException
        readOnlyBuffer.put("lisi".getBytes(StandardCharsets.UTF_8));
    }

}
